layui.define(['jquery', 'layer', 'form', 'xmSelect', 'ajaxCascader', 'laydate', 'table', 'admin', 'upload', 'element', 'dtree'], function (exports) {
    "use strict";

    var MOD_NAME = 'baseAdmin',
        $ = layui.jquery,
        dtree = layui.dtree,
        layer = layui.layer,
        popup = layui.popup,
        table = layui.table,
        admin = layui.admin,
        upload = layui.upload,
        laydate = layui.laydate,
        element = layui.element,
        ajaxCascader = layui.ajaxCascader;

    var baseAdmin = new function () {
        /**
         * 页面初始化渲染
         */
        this.init = function () {

            admin.changeTheme();

            // 多选下拉框
            $(".multi-select").each(function (i, v) {
                let options = $(v).data('options');
                let value = $(v).data('value');
                let field = $(v).data('field');
                let title = $(v).data('title');
                let width = $(v).data('width');
                baseAdmin.renderMultiSelect(field, title, options, value, width);
            })

            // 树形下拉框
            $(".tree-select").each(function (i, v) {
                let options = $(v).data('options');
                let value = $(v).data('value');
                let field = $(v).data('field');
                let title = $(v).data('title');
                let width = $(v).data('width');
                baseAdmin.renderTreeSelect(field, title, options, value, width);
            })

            // 时间
            $(".layui-time").each(function (i, v) {
                let type = $(v).data('time-type');
                let range = $(v).data('time-range');
                baseAdmin.renderTime(this, type, range)
            });

            // 树
            $(".dtree").each(function (i, v) {
                let options = $(v).data('options');
                let value = $(v).data('value');
                let field = $(v).data('field');
                baseAdmin.renderTree(field, options, value);
            });

            this.renderUpImage();
            this.renderUpVideo();
            this.renderUpFile();
            this.renderUpPhoto();
            this.renderUpVod()
        }

        this.renderTree = function (field, options, value) {
            let id = field + '-tree';
            dtree.render({
                elem: "#" + id,
                initLevel: "1",
                data: options,
                line: true,
                checkbar: true, // 设置复选框
                checkbarType: "all",
                // selectInitVal: "001001,001003", // 设置默认值
                done: function () {
                    if (value.length > 0) {
                        dtree.chooseDataInit(id, value);
                    }
                }
            });
            dtree.on("chooseDone('"+id+"')", function (obj) {
                var checkbarParams = obj.checkbarParams; // 选中的所有复选框的参数
                var values = [];
                $.each(checkbarParams, function (i, v) {
                    values.push(v.nodeId);
                });
                $("#"+field).val(values.join(','));
            });
        }

        /**
         * 渲染联动级下拉框
         * @param field
         * @param title
         * @param options
         * @param value
         * @param width
         * @param clicklast
         */
        this.renderTreeSelect = function (field, title, options, value, width = '186', clicklast = false) {
            let tree_name = field + '-tree';
            let config = {
                elem: '#' + tree_name,
                data: options,
                width: width ?? 190,
                placeholder: title,
                clear: true,
                prop: {
                    value: 'id',
                    label: 'name',
                    children: 'children',
                },
                chooseData: value == null ? [] : value,
                clicklast: clicklast ?? false,
            }
            ajaxCascader.load(config);

            // 选择事件
            ajaxCascader.on('click', "#" + tree_name, function () {
                var selector = ".cascader-" + tree_name;
                var values = [];
                $(selector + " .cascader-choose-active").each(function (i, v) {
                    values.push($(this).attr('value'));
                })
                $("#" + field).val(values.join(','));
            });

            // 清空事件
            $(".cascader-" + tree_name + " .cascader-clear").click(function () {
                $("#" + field).val('')
            });
        }
        /**
         * 渲染多选下拉框
         * @param field
         * @param title
         * @param options
         * @param value
         * @param width
         */
        this.renderMultiSelect = function (field, title, options, value, width = '186px') {
            let data = [];
            xmSelect.render({
                el: ("#" + field + '-multi'),
                data: options,
                tips: "请选择" + title,
                initValue: value,
                prop: {
                    name: 'label',
                    value: 'value'
                },
                style: {
                    width: width,
                    fontSize: '12px',
                },
                toolbar: {
                    show: true,
                    showIcon: false,
                    list: ['ALL', 'CLEAR', 'REVERSE'],
                },
                filterable: true,
                model: {
                    // label: {
                    //     type: 'block',
                    //     block: {
                    //         //最大显示数量, 0:不限制
                    //         // showCount: 3,
                    //         //是否显示删除图标
                    //         showIcon: true,
                    //     }
                    // },
                },
                on: function (data) {
                    let arr = data.arr;
                    let values = [];
                    if (arr.length > 0) {
                        $.each(arr, function (ii, vv) {
                            values.push(vv.value);
                        })
                    }
                    $("#" + field).val(JSON.stringify(values));
                    data = values;
                }
            });
            return data;
        }
        /**
         * 渲染时间
         * @param obj
         * @param type
         * @param range
         */
        this.renderTime = function (obj, type, range) {
            laydate.render({
                elem: obj,
                type: type,
                range: range ? true : false,
                rangeLinked: range ? true : false,
                trigger: 'click'
            });
        }

        this.renderUpImage = function () {
            upload.render({
                elem: '.up-image'
                , field: 'file'
                , auto: false
                , choose: function (obj) {
                    let _this = $(this.elem);
                    let maxSize = _this.data('max-size');
                    obj.preview(function (index, file, result) {
                        let totalSize = file.size;
                        if (parseInt(maxSize) > 0 && parseInt(maxSize) < totalSize) {
                            layer.msg('图片大小超过限制');
                            return false;
                        }
                        obj.upload(index, file)
                    });
                }
                , before: function (obj) {
                    layer.load(2)
                }
                , done: function (res) {
                    layer.closeAll('loading'); //关闭loading
                    layer.close();
                    if (res.code === 200) {
                        layer.msg('上传成功');
                        this.item.parent().prev().find('input').val(res.data.url);
                        var elem = this.item.next().next();
                        console.log(elem.find('img').attr('class'))
                        elem.find("img").attr('src', res.data.url);
                    } else {
                        return layer.msg('上传失败')
                    }
                }
                , error: function () {
                    layer.closeAll('loading'); //关闭loading
                    layer.msg('对不起，服务器开小差了，请稍后重试...')
                }
            });
        }

        this.renderUpVideo = function () {
            upload.render({
                elem: '.up-video'
                , field: 'file'
                , accept: 'video'
                , auto: false
                , choose: function (obj) {
                    let _this = $(this.elem);
                    let maxSize = _this.data('max-size');
                    obj.preview(function (index, file, result) {
                        let totalSize = file.size;
                        if (parseInt(maxSize) > 0 && parseInt(maxSize) < totalSize) {
                            layer.msg('视频大小超过限制');
                            return false;
                        }
                        obj.upload(index, file)
                    });
                }
                , before: function (obj) {
                    layer.load(2)
                }
                , done: function (res) {
                    layer.closeAll('loading'); //关闭loading
                    if (res.code === 200) {
                        layer.msg('上传成功');
                        let name = this.item.data('video-field');
                        let cover = this.item.data('cover-field');
                        $("input[name=" + name + "]").val(res.data.url);
                        $("input[name=" + cover + "]").val(res.data.cover);
                        var elem = this.item.next().next();
                        elem.find("img").attr('src', res.data.cover).show();
                        elem.find("a").attr('href', res.data.cover);
                        elem.find("a").removeAttr('onclick');
                    } else {
                        return layer.msg('上传失败')
                    }
                }
                , error: function () {
                    layer.closeAll('loading'); //关闭loading
                    layer.msg('对不起，服务器开小差了，请稍后重试...')
                }
            });
        }

        this.renderUpFile = function () {
            upload.render({
                elem: '.up-file'
                , field: 'file'
                , exts: 'pptx'
                , before: function (obj) {
                    layer.load(2)
                }
                , done: function (res) {
                    layer.closeAll('loading'); //关闭loading
                    layer.close();
                    if (res.code == 200) {
                        layer.msg('上传成功');
                        this.item.parent().prev().find('input').val(res.data.url);
                    } else {
                        return layer.msg('上传失败')
                    }
                }
                , error: function () {
                    layer.closeAll('loading'); //关闭loading
                    layer.msg('对不起，服务器开小差了，请稍后重试...')
                }
            });
        }

        this.renderUpPhoto = function () {
            upload.render({
                elem: '.up-images'
                , url: '/admin/upImage' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
                , field: 'file'
                , multiple: true
                , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    let field = this.elem.data('field');
                    var fileList = $("#uploader-list .file-iteme[data-field='" + field + "']");
                    if (fileList.length >= 9) {
                        layer.msg('最多只能上传9张图片');
                        return false;
                    }
                }
                , done: function (res) {
                    if (res.code === 200) {
                        let field = this.elem.data('field');
                        let btnHtml = '\n' +
                            '                                <div class="handle layui-btn-group" style="display: none;">\n' +
                            '                                    <input type="hidden" name="' + field + '_imgs[]" value="' + res.data.url + '">\n' +
                            '                                    <button type="button" style="height: 18px; line-height: 18px; background-color: #80808000; border: none; border-left: 1px solid white;color: white" ><i class="layui-icon layui-icon-left"></i></button>\n' +
                            '                                    <button type="button" style="height: 18px; line-height: 18px; background-color: #80808000; border: none; border-left: 1px solid white;color: white" ><i class="layui-icon layui-icon-right"></i></button>\n' +
                            '                                    <button type="button" style="height: 18px; line-height: 18px; background-color: #80808000; border: none; border-left: 1px solid white;color: white" ><i class="layui-icon layui-icon-delete"></i></button>\n' +
                            '                                </div>';
                        //上传完毕
                        $('#uploader-list').append(
                            '<div id="" class="file-iteme" data-field="' + field + '">' + btnHtml +
                            '<img style="width: 92px;height: 92px;" src=' + res.data.url + '>' +
                            '<div class="info">图片</div>' +
                            '</div>'
                        );
                        let list = $("#uploader-list .file-iteme[data-field=" + field + "]");
                        let imgs = [];
                        $.each(list, function (i, v) {
                            imgs.push($(v).find('input').val());
                        })
                        $("#uploader-list").parent().parent().prev('input').val(imgs.join(','));
                    } else {
                        layer.msg('上传失败');
                    }
                }
                , error: function () {
                }
            });
        }

        this.renderUpVod = function () {
            upload.render({
                elem: '.up-vod'
                , field: 'file'
                , accept: 'file'
                // , exts: 'mp4'
                , chunked: true
                , chunkSize: 1024 * 1024 * 2
                , auto: false
                , progress: function (n, options) {
                }
                , choose: function (obj) {
                    $("#vodProgress").show();
                    element.progress('vodProgress', '0%');//进度条清0
                    let _this = $(this.elem);
                    var data = this.data;
                    var LENGTH = 10 * 1024 * 1024; //每片文件大小
                    obj.preview(function (index, file, result) {
                        let maxSize = _this.data('max-size');
                        let totalSize = file.size;//文件总大小
                        let totalPage = Math.ceil(totalSize / LENGTH);//总共上传的片数
                        $('#vodChunks').val(totalPage);
                        $('#vodChunk').val('1');
                        $('#vodStatus').val('1');
                        let fileName = file.name;
                        let tempName = baseAdmin.generateUniqueString();
                        var fileExt = fileName.substr(fileName.lastIndexOf('.') + 1);//获取文件后缀
                        fileName = fileName.substr(0, fileName.lastIndexOf('.'));//获取不带后缀的文件名

                        if (parseInt(maxSize) > 0 && parseInt(maxSize) < totalSize) {
                            baseAdmin.layerError('视频大小超过限制');
                            return false;
                        }

                        var progressTimer = setInterval(function () {
                            let totalPage = parseInt($('#vodChunks').val());
                            let page = parseInt($('#vodChunk').val());
                            let status = $('#vodStatus').val();
                            if (parseInt(totalPage) == parseInt(page) && (parseInt(status) == 2 || parseInt(status) == -1)) {
                                $('#vodStatus').val('0');
                                clearInterval(progressTimer);//上传成功或失败停止上传
                            } else {
                                //状态为1的时候上传
                                if (status == 1) {
                                    $('#vodStatus').val('0');
                                    data.fileName = tempName;
                                    data.chunk = page;
                                    data.chunks = totalPage;
                                    data.fileExt = fileExt;
                                    obj.upload(index, file.slice((page - 1) * LENGTH, page * LENGTH));//从文件中截取进行分片上传
                                }
                            }
                        }, 100);
                    });
                }
                , done: function (res) {
                    if (res.data.status == 1) { //分片上传
                        let page = parseInt(res.data.chunk);
                        let totalPage = parseInt(res.data.chunks);
                        element.progress('vodProgress', Math.ceil(page * 100 / totalPage) + '%');//更新进度条
                        page = page + 1;//上传下一片
                        $('#vodChunk').val(page);
                        $('#vodStatus').val('1');
                    } else if (res.data.status == 2) { //上传完成
                        $("#vodProgress").hide();
                        element.progress('vodProgress', '100%');
                        $('#vodStatus').val('2');
                        let field = $(this.elem).data('field');
                        let cover = $(this.elem).data('cover');
                        console.log(cover);
                        $("#" + field).val(res.data.video_url);
                        $("#" + cover).val(res.data.cover_url);
                        layer.msg('上传成功', {time: 1000, anim: 0});
                    } else { //上传错误
                        $('#vodStatus').val(res.data.status);
                        element.progress('vodProgress', '0%');
                        layer.msg(res.data.msg, {time: 3000, anim: 0});
                        $(this.elem).val('');
                    }
                },
                error: function () {
                    layer.msg('上传失败')
                }
            });
        }

        this.generateUniqueString = function () {
            var timestamp = Date.now().toString(36);
            var random = Math.random().toString(36).substr(2, 9);
            return timestamp + random;
        }

        this.layerSuccess = function (msg = '成功') {
            layer.msg(msg, {icon: 1, time: 1000});
        }
        this.layerError = function (msg = '失败') {
            layer.msg(msg, {icon: 2, time: 1000});
        }

        /**
         * 弹窗
         * @param title
         * @param url
         * @param w
         * @param h
         * @param full
         */
        this.layerOpen = function (title, url, w = null, h = null, full = false) {
            if (w === null) {
                w = ($(window).width() * 0.9);
            }
            if (h === null) {
                h = ($(window).height() - 50);
            }
            let index = layer.open({
                type: 2,
                area: [w + 'px', h + 'px'],
                fix: false, //不固定
                maxmin: true,
                shadeClose: true,
                shade: 0.4,
                title: title,
                content: url,
                skin: 'open-class',
            });
            if (full) {
                layer.full(index);
            }
        }
        /**
         * 确认操作
         * @param title
         * @param ids
         * @param uri
         */
        this.layerConfirm = function (title, ids, uri) {
            layer.confirm(title, function (index) {
                try {
                    baseAdmin.ajaxSubmit({ids: ids}, uri);
                    layer.msg('成功', {icon: 1, time: 1000}, function () {
                        tableReload();
                        layer.close(index);
                    });
                } catch (e) {
                    popup.failure(e.message);
                }
            });
        }
        /**
         * 抛出异常
         * @param msg
         */
        this.throwError = function (msg) {
            throw new Error(msg);
        }
        /**
         * 提交
         * @param data
         * @param uri
         * @param method
         * @returns {null}
         */
        this.ajaxSubmit = function (data, uri, method = 'post') {
            var res = null;
            $.ajax({
                url: uri,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json',
                type: method,
                async: false,
                success: function (result) {
                    if (result.code === 200) {
                        res = result.data;
                    } else {
                        popup.success(result.message);
                    }
                }, error: function () {
                    baseAdmin.throwError('请求异常');
                }
            });
            return res;
        }
    };
    exports(MOD_NAME, baseAdmin);
})
